package com.jushu.storbox.view.resolve;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Color;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.jushu.storbox.R;
import com.jushu.storbox.ShareDriveApplication;
import com.jushu.storbox.actions.ActionShare;
import com.jushu.storbox.actions.FolderAction;
import com.jushu.storbox.adapter.MyReceveShareDisplayAdapter;
import com.jushu.storbox.callback.ShareNodeAuthorSort;
import com.jushu.storbox.callback.ShareNodeTimeSort;
import com.jushu.storbox.callback.ShareNodeTypeSort;
import com.jushu.storbox.constant.ClientConfig;
import com.jushu.storbox.constant.Constant;
import com.jushu.storbox.constant.MessageCode;
import com.jushu.storbox.constant.ReceiverConstent;
import com.jushu.storbox.constant.UiConstant;
import com.jushu.storbox.database.DAOFactory;
import com.jushu.storbox.database.IShareINodeDao;
import com.jushu.storbox.entities.FileFolderInfo;
import com.jushu.storbox.entities.FileType;
import com.jushu.storbox.entities.ShareINode;
import com.jushu.storbox.handler.ClientExceptionRelateHandler;
import com.jushu.storbox.manager.CatchManager;
import com.jushu.storbox.operation.group.MyReceveShareOperation;
import com.jushu.storbox.view.dialog.AbsPopupMenuDialog;
import com.jushu.storbox.vo.PagedList;
import com.huawei.sharedrive.sdk.android.exception.ClientException;
import com.huawei.sharedrive.sdk.android.modelV2.request.SharedUserV2;
import com.huawei.sharedrive.sdk.android.modelV2.response.INodeShareV2;
import com.kennyc.view.MultiStateView;

public class MyReceveShareDisplayResolve
        extends MyShareDisplayResolve<INodeShareV2, MyReceveShareOperation<INodeShareV2>, MyReceveShareDisplayAdapter>
        implements MyReceveShareOperation<INodeShareV2> {
    private Button button;
    List<INodeShareV2> datas = new ArrayList<INodeShareV2>();
    private String clickedItemOwnerId = null;
    private int pageNum = 0;
    private MultiStateView multiStateView;


    private OnClickListener listener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            multiStateView.setViewState(MultiStateView.ViewState.LOADING);
            loadDataList();
        }
    };

    public MyReceveShareDisplayResolve(Context context) {
        super(context);
    }

    public MyReceveShareDisplayResolve(Context context, MultiStateView multiStateView) {
        super(context);
        this.multiStateView = multiStateView;
		multiStateView.getView(MultiStateView.ViewState.ERROR).findViewById(R.id.button1).setOnClickListener(listener);
    }

    @Override
    protected final MyReceveShareDisplayAdapter initTemplateAdapter() {
        return new MyReceveShareDisplayAdapter(context, datas);
    }

    @Override
    protected final MyReceveShareOperation<INodeShareV2> initAdapterOperation() {
        return this;
    }

    @Override
    public void binddingAdapter() {
        // TODO Auto-generated method stub
        super.binddingAdapter();

    }

    @Override
    protected void clickItem(View clickView, int position, long id, INodeShareV2 data) {
        ImageView stateImage = (ImageView) clickView.findViewById(R.id.item_filestateupdate_img);
        stateImage.setVisibility(View.GONE);
        clickedItemOwnerId = data.getOwnerId().toString();
        ShareINode shareNode = CatchManager.getInstance().getShareINode(data);
        if (shareNode != null) {
            shareNode.setItemViewed(IShareINodeDao.ITEM_BEEN_VIEWED);
            DAOFactory.instance(context).getShareINodeDao().updateFolderOrFile(shareNode);
        }
        CatchManager.getInstance().removeNewShareShipNode(data);

        int count = CatchManager.getInstance().getNewShareShipCount();
        if (count <= 0) {
            Intent noNewShareShip = new Intent();
            noNewShareShip.setAction(ReceiverConstent.NO_NEW_SHARE_SHIP_FIND);
            context.sendBroadcast(noNewShareShip);
        }

        if (data.getType() == FileType.File.value()) {
            openFile(data);
        } else if (data.getType() == FileType.Folder.value()) {
            new FolderAction().openFolder(context, MessageCode.OPEN_FOLDER, data.getOwnerId().toString(),
                    data.getNodeId().toString(), data.getName(), Constant.FIRST_PAGE_INDEX, handler);
        } else {
        }
    }

    @Override
    public final void onDownloadItem(int index, INodeShareV2 info) {
    }

    @Override
    public void onSaveItem(int index, INodeShareV2 info) {
    }

    protected void openFolder(String ownerId, PagedList<FileFolderInfo> pageList) {
    }

    protected void openFile(INodeShareV2 data) {
        new ActionShare().openOtherShareINodeFile(context, data, handler);
    }

    @Override
    public final void onExitShare(int index, final INodeShareV2 info) {
        AbsPopupMenuDialog cancelDialog = new AbsPopupMenuDialog(context, R.style.dialog_upload,
                R.layout.dialog_filedelete) {
            public void onInflaterFinished(View conventView) {
                Button dialog_cancal = (Button) conventView.findViewById(R.id.dialog_add_file_cancal_bt);
                Button dialog_OK = (Button) conventView.findViewById(R.id.dialog_add_file_ok_bt);
                TextView dialog_prompt_tv = (TextView) conventView.findViewById(R.id.dialog_prompt_tv);
                dialog_prompt_tv.setText(context.getString(R.string.tip_user_exit_share));
                dialog_cancal.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dismiss();
                    }
                });
                dialog_OK.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dismiss();
                        SharedUserV2 sharedUser = new SharedUserV2();
                        sharedUser.setId(ShareDriveApplication.getInstance().getWnerID());
                        sharedUser.setType(null);
                        new ActionShare().deleteShareShips(context, sharedUser, info, handler);
                    }
                });
            }
        };
        cancelDialog.show();
    }

    @Override
    protected void getMoreDataList() {
        new ActionShare().getSharedResourceToMe(context, pageNum, Constant.MAX_SHARE_COUNT, Constant.ALL_FILL, handler);
    }

    protected void loadDataList() {
        pageNum = 0;
        new ActionShare().getSharedResourceToMe(context, pageNum, Constant.MAX_SHARE_COUNT, Constant.ALL_FILL, handler);
    }

    ClientExceptionRelateHandler handler = new ClientExceptionRelateHandler() {
        @SuppressWarnings("unchecked")
        @Override
        public void handleMessage(Message msg) {
            if (msg.obj instanceof ClientException && null != multiStateView) {
                multiStateView.setViewState(MultiStateView.ViewState.CONTENT);
            } else if (null != multiStateView) {
                multiStateView.setViewState(MultiStateView.ViewState.CONTENT);
            }
            switch (msg.what) {
                case MessageCode.OPEN_FOLDER:
                    openFolder(clickedItemOwnerId, (PagedList<FileFolderInfo>) msg.obj);
                    break;
                case UiConstant.SHARE_ACTION_GET_SHARE_RESOURCE_TOME:
                    onRefreshComplete();
                    List<INodeShareV2> listdata = (List<INodeShareV2>) msg.obj;
                    if (pageNum == 0) {
                        adapter.cleanListDatasOnly();
                    }
                    adapter.addDatas(listdata);
                    adapter.notifyDataSetChanged();
                    if (listdata.size() > Constant.MAX_SHARE_COUNT) {
                        pageNum++;
                    }
                    break;
                case UiConstant.SHARE_ACTION_GET_SHARE_RESOURCE_BYME:
                    break;
                case UiConstant.SHARE_ACTION_DELETE_SHARE_SHIPS_SUCCESS:
                    adapter.removeData((INodeShareV2) msg.obj);
                    break;
                default:
                    super.handleMessage(msg);
            }
        }

        @Override
        protected void onHandlerBefore(Message msg, String errorCode) {
            onRefreshComplete();
            super.onHandlerBefore(msg, errorCode);
        }

        @Override
        public Context getContext() {
            return context;
        }
    };

    public void shareSortByFileName(int sortType) {
        adapter.sort(new ShareNodeTypeSort(sortType));
        writePreferenceForSort(UiConstant.SHARE_RECIVE_FILENAME_SORT, sortType);
    }

    public void shareSortByAuthorName(int sortType) {
        adapter.sort(new ShareNodeAuthorSort(sortType));
        writePreferenceForSort(UiConstant.SHARE_RECIVE_AUTHOR_SORT, sortType);
    }

    public void shareSortByShareTime(int sortType) {
        adapter.sort(new ShareNodeTimeSort(sortType));
        writePreferenceForSort(UiConstant.SHARE_RECIVE_TIME_SORT, sortType);
    }

    void writePreferenceForSort(String str, int sortType) {
        SharedPreferences preference = context.getSharedPreferences(ClientConfig.settings, Context.MODE_APPEND);
        Editor edit = preference.edit();
        edit.putInt(str, sortType);
        edit.putInt(UiConstant.SHARE_RECIVE_CURRENT_SORT, sortType);
        edit.commit();
    }

}
